<template>
	<view class="apply-container">
		<view class="form-section card">
			<view class="section-title">水产品信息</view>
			<view class="form-item">
				<view class="label required">水产品名称/规格</view>
				<view class="input-wrapper">
					<picker mode="selector" :range="productOptions" range-key="name" @change="onProductChange">
						<view class="picker-value" :class="{ placeholder: !form.product_name }">
							{{ form.product_name || '请选择水产品' }}
						</view>
					</picker>
					<text class="arrow-right">&#xe6a3;</text>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label required">数量</view>
				<view class="input-wrapper">
					<input 
						type="number" 
						v-model="form.quantity" 
						placeholder="请输入数量" 
						class="input"
						@input="calculateTotal"
					/>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label">单价 (元)</view>
				<view class="input-wrapper">
					<text class="value">{{ form.unit_price }}</text>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label">总金额 (元)</view>
				<view class="input-wrapper">
					<text class="value price">{{ form.total_amount }}</text>
				</view>
			</view>
		</view>
		
		<view class="form-section card">
			<view class="section-title">配送信息</view>
			<view class="form-item">
				<view class="label required">期望送达日期时间</view>
				<view class="input-wrapper">
					<picker mode="date" :start="startDate" :end="endDate" @change="onDateChange">
						<view class="picker-value" :class="{ placeholder: !form.delivery_date }">
							{{ form.delivery_date || '请选择日期' }}
						</view>
					</picker>
					<text class="arrow-right">&#xe6a3;</text>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label"></view>
				<view class="input-wrapper">
					<picker mode="time" :start="startTime" :end="endTime" @change="onTimeChange">
						<view class="picker-value" :class="{ placeholder: !form.delivery_time }">
							{{ form.delivery_time || '请选择时间' }}
						</view>
					</picker>
					<text class="arrow-right">&#xe6a3;</text>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label required">配送单元</view>
				<view class="input-wrapper">
					<picker 
						mode="selector" 
						:range="unitOptions" 
						range-key="name" 
						@change="onUnitChange"
					>
						<view class="picker-value" :class="{ placeholder: !selectedUnit.name }">
							{{ selectedUnit.name || '请选择配送单元' }}
						</view>
					</picker>
					<text class="arrow-right">&#xe6a3;</text>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label">详细地址</view>
				<view class="input-wrapper textarea-wrapper">
					<textarea 
						v-model="form.delivery_address_detail" 
						placeholder="请输入详细地址信息，如楼层、房号等" 
						class="textarea"
					></textarea>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label required">联系人姓名</view>
				<view class="input-wrapper">
					<input 
						type="text" 
						v-model="form.contact_name" 
						placeholder="请输入联系人姓名" 
						class="input"
					/>
				</view>
			</view>
			
			<view class="form-item">
				<view class="label required">联系电话</view>
				<view class="input-wrapper">
					<input 
						type="number" 
						v-model="form.contact_phone" 
						placeholder="请输入联系电话" 
						class="input"
					/>
				</view>
			</view>
		</view>
		
		<view class="submit-section">
			<button class="submit-btn" @click="submitForm">提交申请</button>
		</view>
	</view>
</template>

<script>
	import { createWaterDelivery, getUserAvailableUnits } from '@/api/services.js'
	
	export default {
		data() {
			const now = new Date()
			const tomorrow = new Date(now)
			tomorrow.setDate(tomorrow.getDate() + 1)
			
			const formatDate = (date) => {
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			}
			
			return {
				form: {
					product_name: '',
					quantity: '',
					unit_price: '0.00',
					total_amount: '0.00',
					delivery_date: '',
					delivery_time: '',
					unit_id: null,
					delivery_address_detail: '',
					contact_name: '',
					contact_phone: ''
				},
				selectedUnit: {
					id: null,
					name: ''
				},
				productOptions: [
					{ name: '某品牌桶装水 18.9L', price: 18.00 },
					{ name: '某品牌瓶装水 500ml*24', price: 36.00 },
					{ name: '某品牌瓶装水 350ml*24', price: 28.00 }
				],
				unitOptions: [],
				loading: false,
				selectedProductIndex: -1,
				startDate: formatDate(tomorrow),
				endDate: formatDate(new Date(now.setMonth(now.getMonth() + 1))),
				startTime: '09:00',
				endTime: '18:00'
			}
		},
		onLoad() {
			// 尝试获取用户信息并预填联系人信息
			const userInfo = uni.getStorageSync('userInfo')
			if (userInfo) {
				this.form.contact_name = userInfo.name || ''
				this.form.contact_phone = userInfo.phone || ''
			}
			
			// 加载真实的单元数据
			this.loadUnits()
		},
		methods: {
			// 选择水产品
			onProductChange(e) {
				const index = e.detail.value
				this.selectedProductIndex = index
				const product = this.productOptions[index]
				this.form.product_name = product.name
				this.form.unit_price = product.price.toFixed(2)
				this.calculateTotal()
			},
			
			// 计算总金额
			calculateTotal() {
				if (this.form.quantity && this.form.unit_price) {
					const quantity = parseInt(this.form.quantity)
					const unitPrice = parseFloat(this.form.unit_price)
					if (!isNaN(quantity) && !isNaN(unitPrice)) {
						this.form.total_amount = (quantity * unitPrice).toFixed(2)
						console.log('计算总金额:', `数量:${quantity} × 单价:${unitPrice} = ${this.form.total_amount}`)
					}
				}
			},
			
			// 加载配送单元数据
			loadUnits() {
				this.loading = true
				console.log('开始加载用户单元列表...')
				
				getUserAvailableUnits()
					.then(units => {
						console.log('获取到的用户单元列表:', JSON.stringify(units, null, 2))
						
						if (units && units.length > 0) {
							// 转换数据格式
							this.unitOptions = units.map(unit => ({
								id: unit.unit_id,
								name: `${unit.building_name} ${unit.floor_label} ${unit.unit_number}`
							}))
							console.log('处理后的单元列表:', JSON.stringify(this.unitOptions, null, 2))
						} else {
							uni.showToast({
								title: '未找到可用单元',
								icon: 'none'
							})
							this.unitOptions = []
						}
					})
					.catch(error => {
						console.error('获取用户单元列表失败:', error)
						uni.showToast({
							title: '获取单元列表失败',
							icon: 'none'
						})
						// 使用默认数据作为备选
						this.unitOptions = [
							{ id: 42, name: '会议中心 1层 W002' }
						]
					})
					.finally(() => {
						this.loading = false
					})
			},
			
			// 选择日期
			onDateChange(e) {
				this.form.delivery_date = e.detail.value
			},
			
			// 选择时间
			onTimeChange(e) {
				this.form.delivery_time = e.detail.value
			},
			
			// 选择配送单元
			onUnitChange(e) {
				const index = e.detail.value
				const selectedUnit = this.unitOptions[index]
				this.selectedUnit = selectedUnit
				this.form.unit_id = selectedUnit.id
				console.log('已选择配送单元:', selectedUnit.name, 'ID:', selectedUnit.id)
			},
			
			// 验证表单
			validateForm() {
				if (!this.form.product_name) {
					uni.showToast({
						title: '请选择水产品',
						icon: 'none'
					})
					return false
				}
				
				if (!this.form.quantity || parseInt(this.form.quantity) <= 0) {
					uni.showToast({
						title: '请输入有效的数量',
						icon: 'none'
					})
					return false
				}
				
				if (!this.form.delivery_date || !this.form.delivery_time) {
					uni.showToast({
						title: '请选择期望送达时间',
						icon: 'none'
					})
					return false
				}
				
				if (!this.form.unit_id) {
					uni.showToast({
						title: '请选择配送单元',
						icon: 'none'
					})
					return false
				}
				
				if (!this.form.contact_name) {
					uni.showToast({
						title: '请输入联系人姓名',
						icon: 'none'
					})
					return false
				}
				
				if (!this.form.contact_phone) {
					uni.showToast({
						title: '请输入联系电话',
						icon: 'none'
					})
					return false
				}
				
				// 简单的手机号验证
				if (!/^1\d{10}$/.test(this.form.contact_phone)) {
					uni.showToast({
						title: '请输入有效的手机号',
						icon: 'none'
					})
					return false
				}
				
				return true
			},
			
			// 提交表单
			async submitForm() {
				if (!this.validateForm()) {
					return
				}
				
				// 确保重新计算总金额
				const quantity = parseInt(this.form.quantity)
				const unitPrice = parseFloat(this.form.unit_price)
				const totalAmount = quantity * unitPrice
				
				// 构建API请求数据
				const data = {
					product_name: this.form.product_name,
					quantity: quantity,
					unit_price: unitPrice,
					total_amount: totalAmount,
					expected_delivery_time: `${this.form.delivery_date}T${this.form.delivery_time}:00`,
					unit_id: this.form.unit_id,
					delivery_address: this.selectedUnit.name + (this.form.delivery_address_detail ? ` (${this.form.delivery_address_detail})` : ''),
					contact_name: this.form.contact_name,
					contact_phone: this.form.contact_phone
				}
				
				// 打印提交的数据进行调试
				console.log('提交送水服务数据:', JSON.stringify(data, null, 2))
				console.log('数值验证 - 总金额:', `${quantity} × ${unitPrice} = ${totalAmount}`)
				
				uni.showLoading({
					title: '提交中...'
				})
				
				try {
					await createWaterDelivery(data)
					
					uni.hideLoading()
					uni.showToast({
						title: '申请成功',
						icon: 'success'
					})
					
					// 返回列表页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
					
				} catch (error) {
					uni.hideLoading()
					console.error('提交送水服务申请失败', error)
					
					// 显示详细错误信息
					let errorMsg = '申请失败，请重试'
					if (error && error.detail) {
						errorMsg = error.detail
					}
					
					uni.showToast({
						title: errorMsg,
						icon: 'none',
						duration: 3000
					})
					
					// 如果是方法不允许错误，提示开发者可能需要修改API方法
					if (error && error.detail && error.detail.includes('方法') && error.detail.includes('不被允许')) {
						console.warn('API方法错误，可能需要更改API调用方式或联系后端开发者')
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	.apply-container {
		padding: 20rpx;
		background-color: #F8F8F8;
		min-height: 100vh;
		
		.form-section {
			margin-bottom: 20rpx;
			
			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 20rpx;
				padding-left: 20rpx;
				border-left: 8rpx solid #2979ff;
			}
			
			.form-item {
				display: flex;
				margin-bottom: 30rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.label {
					width: 200rpx;
					font-size: 28rpx;
					color: #333;
					padding-top: 6rpx;
					
					&.required:before {
						content: '*';
						color: #ff5a5f;
						margin-right: 6rpx;
					}
				}
				
				.input-wrapper {
					flex: 1;
					position: relative;
					
					.input, .picker-value, .value {
						width: 100%;
						height: 70rpx;
						line-height: 70rpx;
						font-size: 28rpx;
						color: #333;
						padding: 0 20rpx;
						background-color: #f5f5f5;
						border-radius: 8rpx;
					}
					
					.placeholder {
						color: #999;
					}
					
					.arrow-right {
						position: absolute;
						right: 20rpx;
						top: 50%;
						transform: translateY(-50%);
						color: #999;
						font-family: "iconfont";
					}
					
					.price {
						color: #ff5a5f;
						font-weight: bold;
					}
					
					&.textarea-wrapper {
						height: auto;
						
						.textarea {
							width: 100%;
							height: 180rpx;
							font-size: 28rpx;
							color: #333;
							padding: 20rpx;
							background-color: #f5f5f5;
							border-radius: 8rpx;
						}
					}
				}
			}
		}
		
		.submit-section {
			margin-top: 40rpx;
			padding: 0 40rpx;
			
			.submit-btn {
				background-color: #2979ff;
				color: #fff;
				border-radius: 45rpx;
				font-size: 32rpx;
				height: 90rpx;
				line-height: 90rpx;
			}
		}
	}
</style> 